package com.shop;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.provider.SyncStateContract;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.shop.adapter.MainFragmentAdapter;
import com.shop.inteface.FragmentDelegate;
import com.shop.model.Product;
import com.shop.third.DividerItemDecoration;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class MainFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private FragmentDelegate mListener;
    //实现了下拉刷新头的layout，listview就在它里面
    private PtrClassicFrameLayout mPtrFrame;

    RecyclerView listView;

    //adapter所使用的数据
    List<Product> products = new ArrayList();
    //显示列表不使用listview了，使用更时髦的recyclerview吧
    private MainFragmentAdapter adapter;
    public MainFragment() {

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment StudentFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View chatView = inflater.inflate(R.layout.fragment_main, container, false);

        listView = (RecyclerView) chatView.findViewById(R.id.recyclerView);


        //设置recyclerView的Manager
        listView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));

        mPtrFrame = (PtrClassicFrameLayout) chatView.findViewById(R.id.rotate_header_list_view_frame);
        //使用了自定义的刷新头类：RefreashHeaderView
        RefreashHeaderView rhv = new RefreashHeaderView(this.getContext());
        mPtrFrame.setHeaderView(rhv);
        mPtrFrame.addPtrUIHandler(rhv);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //在这里，重新加载后台数据
                startGettingProducts();

            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        adapter=new MainFragmentAdapter(MainFragment.this.getContext(),products);
        listView.setAdapter(this.adapter);
        //设置RecyclerView的Item间的分割线
//        listView.addItemDecoration(new DividerItemDecoration(this.getContext(),DividerItemDecoration.VERTICAL_LIST));
        return chatView;
    }

    //网服务端获取学生们，一次获取一页（10个）
    private void startGettingProducts() {
        AsyncHttpClient uploadTask = new AsyncHttpClient();
        //发出get请求，获取一页的商品信息
        //TODO：修改后台api
        uploadTask.get(Constants.serverHost + "/api/app/getAllProducts",
                new AsyncHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        String jsonStr = new String(responseBody);
                        //把字符串转成JsonObject
                        try {
                            JSONObject jo = new JSONObject(jsonStr);
                            int res = jo.getInt("result");
                            if (res == 0) {
                                //没成功
                                Log.e("getProducts", jo.getString("errorMsg"));
                            } else {
                                //成功。
                                //既然是刷新，那么把原来的清空
                                products.clear();
                                JSONArray ja = jo.getJSONArray("products");
                                for (int i = 0; i < ja.length(); i++) {
                                    JSONObject jsonStudent = ja.getJSONObject(i);
                                    Product product = new Product(jsonStudent);
                                    products.add(product);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                        //这种方式会引起PtrClassicFrameLayout崩溃
                        //listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                        //隐藏刷新头
                        mPtrFrame.refreshComplete();

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          byte[] responseBody, Throwable error) {
                        mPtrFrame.refreshComplete();
                    }
                });


    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }



}
